<script setup>
import { ref, watch } from "vue";
import { indexOf } from "lodash";
import attachApi from "@/apis/system/upload.js";
import config from "@cwd/config/crud";
import { message } from "@/utils/message";
import WdUploadImg from "@cwd/widgets/wd-upload-img";
import tool from "@/utils/tool";

const emit = defineEmits(["getPickerFiles"]);
const uploadImgRef = ref(null);

const props = defineProps({
  title: { type: String, default: "图片管理" },
  maxLength: {
    type: [String, Number],
    default: 0,
    validator: (value) => Number(value) >= 0,
  },
  isIframe: { type: Boolean, default: false },
});

const openPicker = ref(false);
const open = () => {
  openPicker.value = true;
};
const close = () => {
  openPicker.value = false;
};

const loading = ref(false);
const dataList = ref([]);
const total = ref(0);
const openPagination = ref(false);
const requestParams = ref({
  cate: 0,
  page: 1,
  pageSize: 15,
});
const imgCheckedIds = ref([]);
const imgCheckedItems = ref([]);

const selectAttach = (item) => {
  if (!item?.attach_id) {
    message("图片数据无效", { type: "error",...item });
    console.error("Invalid item:", item);
    return;
  }
  const max = Number(props.maxLength);
  const index = imgCheckedIds.value.indexOf(item.attach_id);
  if (index !== -1) {
    imgCheckedIds.value.splice(index, 1);
    imgCheckedItems.value.splice(index, 1);
    // console.log("Removed item, current items:", imgCheckedItems.value);
  } else {
    if (max > 0 && imgCheckedIds.value.length >= max) {
      message(`最多可选择 ${max} 张图片`, { type: "error" });
      return;
    }
    imgCheckedIds.value.push(item.attach_id);
    imgCheckedItems.value.push({ ...item });
    // console.log("Added item, current items:", imgCheckedItems.value);
  }
};

const handleCheckPic = () => {
  emit("getPickerFiles", props.maxLength == 1 ? imgCheckedItems.value[0] || [] : [...imgCheckedItems.value]);
  imgCheckedIds.value = []; // 清空选中状态
  imgCheckedItems.value = [];
};

const refresh = async () => {
  try {
    loading.value = true;
    const response = config.parseResponseData(
      await attachApi.getPageList(requestParams.value)
    );
    dataList.value = response.rows || [];
    total.value = response.pageInfo?.total || 0;
    openPagination.value = !!response.pageInfo;
  } catch (error) {
    message("获取图片列表失败", { type: "error" });
    console.error("刷新图片列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const pageChangeHandler = async (currentPage) => {
  requestParams.value.page = currentPage;
  await refresh();
};

const openUpload = () => {
  uploadImgRef.value.open();
};

const uploadSuccess = () => {
  refresh();
};

watch(
  () => openPicker.value,
  async (newVal) => {
    if (newVal) {
      await refresh();
    }
  }
);

defineExpose({ open, close });
</script>

<template>
  <el-dialog
    v-model="openPicker"
    :title="props.title"
    :width="isIframe ? '100%' : '880px'"
    class="picker-dialog"
    :modal="false"
  >
    <div class="picker-wrapper">
      <div class="images-box pt-4">
        <div class="picker-image-tools">
          <el-space align="start" wrap class="flex justify-start w-full">
            <el-button
              type="primary"
              @click="handleCheckPic"
              :disabled="imgCheckedIds.length <= 0"
            >
              使用选中图片({{ imgCheckedIds.length }})
            </el-button>
            <el-button type="primary" @click="openUpload">上传图片</el-button>
            <el-input
              style="width: 160px"
              placeholder="请输入图片标题..."
              clearable
            />
          </el-space>
        </div>
        <div class="picker-image-list">
          <el-space
            align="start"
            wrap
            class="flex justify-start w-full"
            style="gap: 0 10px"
          >
            <div
              v-for="(item, index) in dataList"
              :key="item.attach_id"
              class="attachment-item"
              :class="{ active: imgCheckedIds.includes(item.attach_id) }"
              shadow="never"
              style="border: 0"
              @click="selectAttach(item)"
            >
              <div class="flex justify-around w-full flex-col items-center">
                <div class="attach-img">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="tool.attachUrl(item.att_dir)"
                    fit="cover"
                  />
                </div>
                <div class="attach-bottom w-full text-xs cursor-pointer">
                  <div class="attach-title w-full truncate">
                    {{ item.real_name }}
                  </div>
                </div>
              </div>
              <div
                class="attach-select-index absolute flex items-center justify-center font-bold text-white"
              >
                {{ indexOf(imgCheckedIds, item.attach_id) + 1 }}
              </div>
            </div>
          </el-space>
        </div>
        <div v-if="total > 0" class="flex justify-end mt-4">
          <el-pagination
            v-model:current-page="requestParams.page"
            v-model:page-size="requestParams.pageSize"
            :background="true"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="pageChangeHandler"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <wd-upload-img ref="uploadImgRef" @uploadSuccess="uploadSuccess" />
</template>

<style lang="less" scoped>
.picker-dialog {
  z-index: 500;
  .el-dialog__header {
    border-bottom: 1px solid #f1f1f1;
  }
  .el-dialog__body {
    overflow-y: auto;
    max-height: 720px;
    padding: 20px;
  }
  .picker-wrapper {
    display: flex;
    flex-wrap: nowrap;
    width: 100%;
    box-sizing: border-box;
    .images-box {
      width: 100%;
      margin-left: 20px;
      .picker-image-tools {
        padding-bottom: 20px;
        box-sizing: border-box;
      }
      .picker-image-list {
        overflow-y: auto;
        max-height: 540px;
        min-height: 463px;
        .attachment-item {
          width: 110px;
          height: 145px;
          position: relative;
          margin-bottom: 10px;
          &:hover {
            cursor: pointer;
          }
          .el-card__body {
            padding: 0;
          }
          .attach-img {
            width: 100px;
            height: 100px;
            background-color: #f8f8f8;
            border: 2px solid transparent;
            box-sizing: content-box;
            transition: border 0.3s ease;
          }
          &.active .attach-img {
            border-color: var(--el-color-primary);
          }
          .attach-select-index {
            display: none;
            width: 20px;
            height: 20px;
            top: 5px;
            right: 5px;
            border-radius: 50%;
            background: var(--el-color-primary);
          }
          &.active .attach-select-index {
            display: flex;
          }
          .attach-bottom .attach-title {
            width: 100px;
            line-height: 18px;
            padding: 2px 0;
            text-align: center;
          }
        }
      }
    }
  }
}
</style>